package com.bw.module_home.ui

import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.lib_common.arouter.Router
import com.bw.lib_common.base.BaseActivity
import com.bw.module_home.R
import com.bw.module_home.databinding.ActivityVisitBinding
import com.bw.module_home.visit.adapter.VisitAdapter
import com.bw.module_home.visit.adapter.VisitStatusAdapter
import com.bw.module_home.visit.model.VisitEntityItem
import com.bw.module_home.visit.viewmodel.VisitViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
@Route(path = Router.Ui.VisitActivity)
class VisitActivity : BaseActivity<VisitViewModel, ActivityVisitBinding>() {
    private val statusList : List<String> = listOf("全部状态","已通过","驳回","待审核","拒绝")
    private val visitStatusAdapter = VisitStatusAdapter()
    private val visitAdapter = VisitAdapter()
    private var mPosition = 0
    private var visitList = mutableListOf<VisitEntityItem>()
    private val vm: VisitViewModel by viewModels()

    override val mLayoutResId: Int
        get() = R.layout.activity_visit

    override fun initView() {
        super.initView()
        mBinding.visitBack.setOnClickListener {
            finish()
        }
        visitStatusAdapter.data.addAll(statusList)
        mBinding.visitStatusRv.adapter = visitStatusAdapter
        mBinding.visitStatusRv.layoutManager = LinearLayoutManager(this,
            LinearLayoutManager.HORIZONTAL,false)
        visitStatusAdapter.setOnItemClickListener { _, _, position ->
            visitStatusAdapter.setPosition(position)
            mPosition = position
            visitStatusAdapter.notifyDataSetChanged()
            vm.getVisitList()
        }
        mBinding.visitListRv.adapter = visitAdapter
        mBinding.visitListRv.layoutManager = LinearLayoutManager(this)
        visitAdapter.setOnItemClickListener { _, _, _ ->
        }
        mBinding.visitAdd.setOnClickListener {
            ARouter.getInstance().build("/visit/add_visit").navigation()
        }
    }

    override fun initListener() {
        super.initListener()
        vm.getVisitListSuccess.observe(this) { list ->
            // 将 list 转换为 List<VisitEntityItem>
            val flattenedList = list.flatten()
            val reversedList = flattenedList.toMutableList().apply { reverse() }
            visitAdapter.data.clear()
            if (mPosition != 0) {
                val items = reversedList.filter { item ->
                    item.visitStatus == statusList[mPosition]
                }
                visitAdapter.data.addAll(items)
                visitList.addAll(items)
            } else {
                visitAdapter.data.addAll(reversedList)
            }
            visitAdapter.notifyDataSetChanged()
        }
    }


    override fun onResume() {
        super.onResume()
        vm.getVisitList()
    }
}